/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control.admin;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Product;
import persistence.PersistenceFactory;
import persistence.PersistenceInterface;

/**
 *
 * @author isen
 */
public class EditProductServlet extends CreateProductServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PersistenceInterface persistenceManager = PersistenceFactory.getInstance(persistenceMechanism);
        String oldname = request.getParameter("oldname");
        String newname = request.getParameter("ProductName");
        
        if(!oldname.isEmpty()){
            if ( super.validateForm(request) && persistenceManager.productExists(oldname) && !persistenceManager.productExists(newname)) {
                try {
                    Product product = super.generateProductFromRequest(request);
                    if (product != null) {
                        if (persistenceManager.updateProduct(oldname, product)) {
                            request.setAttribute("product", product);
                            gotoURL(productChanged, request, response);
                        } else {
                            request.setAttribute("resultado", "Error to update the newproduct");
                            request.getRequestDispatcher("forms/EditProduct.jsp").forward(request, response);
                        }
                    }
                } catch (Exception e) {
                    request.setAttribute("resultado", "You have to fill in all the form");
                    request.getRequestDispatcher("forms/EditProduct.jsp").forward(request, response);
                }

            } else {
                request.setAttribute("resultado", "the product you want to change doesn't exist or you didn't refill in all the form");
                request.getRequestDispatcher("forms/EditProduct.jsp").forward(request, response);
            }
        }else{
            request.setAttribute("resultado", "Error to fill in the form");
            request.getRequestDispatcher("forms/EditProduct.jsp").forward(request, response);
        }
    }
}
